package com.example;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;

public class TransactionTest {
    public static void main(String[] args) {
        Properties props = new Properties();

        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.228.201:9092,192.168.228.202:9092,192.168.228.203:9092");
        props.put(ProducerConfig.ACKS_CONFIG, "all");
        // 重试次数
        props.put(ProducerConfig.RETRIES_CONFIG, 1);
        // 批次大小
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
        // 等待时间
        props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
        // RecordAccumulator 缓冲区大小
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        props.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "kafka_tx001");

        KafkaProducer<String, String> producer = new KafkaProducer<>(props);

        producer.initTransactions();
        producer.beginTransaction();
        try {
            ProducerRecord<String, String> record = new ProducerRecord<>("first", "hello kafka");
            producer.send(record);

            ProducerRecord<String, String> record2 = new ProducerRecord<>("first", "hello kafka");
            producer.send(record2);

            ProducerRecord<String, String> record3 = new ProducerRecord<>("first", "hello kafka");
            producer.send(record3);
            producer.commitTransaction();
        } catch (Exception e) {
            producer.abortTransaction();
        }




        producer.close();
    }
}
